<template>
 <ul class="list">
  <li :class="{active:categoryIndex==index}" v-for="(item, index) of allCities" :key="index" @click="handleLetterClick(item,index)" @touchstart="handleTouchStart" @touchmove="handleTouchMove" @touchend="handleTouchEnd" :ref="[...item.title]">{{item.title}}</li>
 </ul>
</template>
<script>
export default {
  name: 'CityAlphabet',
  props: ['allCities'],
  data () {
    return {
      touchStatus: false,
      categoryIndex: 0
    }
  },
  computed: {
    // 把 传过来的allcities对象转换为数组
    letters () {
      const letters = []
      // allCities是普通对象 不能迭代 需要通过Array.from 绕过
      const arr = Array.from(this.allCities)
      for (const i of arr) {
        letters.push(i.title)
      }
      console.log(letters)
      return letters
    }
  },
  methods: {
    handleLetterClick (item, index) {
      this.$emit('change', item.title)
      this.categoryIndex = index
    },
    handleTouchStart () {
      this.touchStatus = true
    },
    handleTouchMove (e) {
      if (this.touchStatus) {
        if (this.timer) {
          clearTimeout(this.timer)
        }
        this.timer = setTimeout(() => {
          // 定时器 函数节流  提高网页性能
          const touchY = e.touches[0].clientY - 70
          // 70 是搜索框和头部的高度  下面的 75是第一个字母a到搜索框下边圆的距离
          const index = Math.floor((touchY - 75) / 16)
          if (index >= 0 && index < this.letters.length) {
            this.$emit('change', this.letters[index])
            this.categoryIndex = index
          }
        }, 10)
      }
    },
    handleTouchEnd () {
      this.touchStatus = false
    }
  }
}
</script>
<style lang="stylus" scoped>
@import '~@/assets/style/varibles.styl'
.list
 position :fixed
 top: 12rem
 right: 1rem
 font-size : 1.2rem
 line-height : 1.5rem
 color: $bgColor
 .active {
 background:  #FF00FF
 border-radius : 100%
 text-align: center
 width : 1.3rem
 height : 1.3rem
}
</style>
